﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
using Misuzilla.Crigate;

namespace Crigate
{
    class ApplicationMain : ApplicationContext
    {
        private Settings _settings = new Settings();
        private Server _server;
        private NotifyIcon _notifyIcon;
        private const String Name = "Crigate";
        
        public Boolean Initialize()
        {
            Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
            Int32 port = _settings.Port;
            IPAddress ipAddr = _settings.LocalOnly ? IPAddress.Loopback : IPAddress.Any;

            ContextMenu ctxMenu = new ContextMenu();
            ctxMenu.MenuItems.Add(new MenuItem("終了(&X)", ContextMenuItemExit));
            _notifyIcon = new NotifyIcon
                              {
                                    Text        = String.Format("{0} (IP: {1} / ポート {2})", Name, ipAddr, port)
                                  , ContextMenu = ctxMenu
                                  , Icon        = Resource.ApplicationIcon
                              };


            _server = new Server();
            _server.Authorizer = new SettingsAuthorizer(_settings);
            _server.SessionStartedReceived += new EventHandler<SessionStartedEventArgs>(_server_SessionStartedReceived);
            try
            {
                _server.Encoding = (String.Compare(_settings.Encoding, "UTF-8", true) == 0)
                                    ? new UTF8Encoding(false) // BOM なし
                                    : Encoding.GetEncoding(_settings.Encoding);
            }
            catch (ArgumentException)
            {
                _server.Encoding = Encoding.GetEncoding("ISO-2022-JP");
            }

            // start
            try
            {
                _server.Start(ipAddr, port);
                _notifyIcon.Visible = true;
                _notifyIcon.ShowBalloonTip(1000 * 10, Name, String.Format("IRCサーバがポート {0} で開始されました。", port), ToolTipIcon.Info);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message, Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            return true;
        }

        void Application_ApplicationExit(object sender, EventArgs e)
        {
            _server.Stop();
            _notifyIcon.Visible = false;
        }

        void _server_SessionStartedReceived(object sender, SessionStartedEventArgs e)
        {
            _notifyIcon.ShowBalloonTip(1000 * 10, Name, String.Format("ユーザ {0} がサーバに接続しました。", e.UserName), ToolTipIcon.Info);
        }

        private void ContextMenuItemExit(Object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}
